#include <string>
#include <thread>
#include <iostream>

#include <zmq.hpp>

// zmq的router-dealer模式，router 会接收到 两 frame 的消息 ，第一帧是 发送端的 标识。第二帧才是 真正的数据。
// 同时 router 回复的时候，也要 发送两 frame

int main() {
    using namespace std::chrono_literals;

    // initialize the zmq context with a single IO thread
    zmq::context_t context{1};

    // construct a REP (reply) socket and bind to interface
    zmq::socket_t socket{context, zmq::socket_type::router};
    socket.bind("tcp://127.0.0.1:5555");

    // prepare some static data for responses
    const std::string data{"World"};

    for (;;) {
        zmq::message_t addr;
        zmq::message_t request;

        // receive a request from client
        socket.recv(addr, zmq::recv_flags::none);

        socket.recv(request, zmq::recv_flags::none);
        std::cout << "Received " << request.to_string() << std::endl;
        // simulate work
        std::this_thread::sleep_for(1s);

        // send the reply to the client
        socket.send(addr, zmq::send_flags::sndmore);
        socket.send(zmq::buffer(data), zmq::send_flags::none);
    }

    return 0;
}